////////////////////////////////////////////////////////
//
//  Copyright(C), 2005-2022, GEC Tech. Co., Ltd.
//  www.yueqian.com.cn  ALL RIGHT RESERVED
//
//  文件: broadcast-recv.c
//  描述: 接收UDP广播数据，然后简单输出到终端
//
///////////////////////////////////////////////////////

#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <errno.h>

int main(int argc, char const *argv[])
{
    // 创建UDP套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

    // 获取指定网卡IP
    struct ifreq ifr;
    strcpy(ifr.ifr_ifrn.ifrn_name, "ens36");

    // 绑定地址
    struct sockaddr_in addr = {0};
    addr.sin_family = AF_INET;
    addr.sin_addr = ((struct sockaddr_in *)&(ifr.ifr_ifru.ifru_addr))->sin_addr;
    addr.sin_port = htons(50021);
    if(bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) == 0)
        printf("绑定地址成功\n");
    else
        perror("绑定地址失败");

    // 等待UDP数据
    struct sockaddr_in peeraddr = {0};
    socklen_t len = sizeof(peeraddr);
    char buf[100] = {0};
    printf("等待UDP数据...\n");
    int n = recvfrom(sockfd, buf, 100, 0,
                     (struct sockaddr *)&peeraddr, &len);
    if(n == -1)
    {
        perror("recvfrom出错");
        exit(0);
    }

    printf("收到【%s:%hu】消息:%s\n", inet_ntoa(peeraddr.sin_addr),
                                      ntohs(peeraddr.sin_port), buf);

    return 0;
}